package database

import (
	"blog2/util"
	"strconv"
)

func AddBlogCountToBlog(blogId int, feild string) error {
	redisClient := GetBlogRedisConnection()
	newVal, err := redisClient.HIncrBy(GetBlogsCountKey(blogId), feild, 1).Result()
	if err != nil {
		util.LogRus.Infof("Error adding like to blog, blogId: %d, error: %s", blogId, err)
		return err
	}
	util.LogRus.Infof("Add like to blog success, blogId: %d, like count: %d", blogId, newVal)
	return nil
}

func DecBlogCountToBlog(blogId int, feild string) error {
	redisClient := GetBlogRedisConnection()
	newVal, err := redisClient.HIncrBy(GetBlogsCountKey(blogId), feild, -1).Result()
	if err != nil {
		util.LogRus.Infof("Error dec like to blog, blogId: %d, error: %s", blogId, err)
		return err
	}
	util.LogRus.Infof("Dec like to blog success, blogId: %d, like count: %d", blogId, newVal)
	return nil
}

func GetBlogCountFromRedis(blogId int) map[string]int {
	redisClient := GetBlogRedisConnection()
	result := make(map[string]int)
	key := GetBlogsCountKey(blogId)
	values, err := redisClient.HGetAll(key).Result()
	if err != nil {
		util.LogRus.Infof("Error getting blog count from redis, blogId: %d, error: %s", blogId, err)
		return nil
	}
	for k, v := range values {
		result[k], _ = strconv.Atoi(v)
	}
	return result
}

func DelBlogCountFromRedis(blogId int) {
	redisClient := GetBlogRedisConnection()
	key := GetBlogsCountKey(blogId)
	redisClient.Del(key)
	util.LogRus.Infof("Delete blog count from redis, blogId: %d", blogId)
}

func GetToken(refreshToken string) string {
	redisClient := GetBlogRedisConnection()
	key := GetRefreshTokeKey(refreshToken)
	token, err := redisClient.Get(key).Result()
	if err == nil {
		return token
	}
	return ""
}

func SetToken(refreshToken, token string) {
	redisClient := GetBlogRedisConnection()
	key := GetRefreshTokeKey(refreshToken)
	redisClient.Set(key, token, TOEKEN_EXPIRE) // 7 days
	util.LogRus.Infof("Set refresh token to redis, refreshToken: %s, token: %s", refreshToken, token)
}
